#include "Tile.h"

#include "SGD Wrappers\CSGD_TextureManager.h"

#include "Game.h"
#include "Entity.h"
#include "ObjectManager.h"
#include "EventSystem.h"
#include "GamePlayState.h"
#include "TileManager.h"

Tile::Tile(int tileType, int x, int y, int width, int height, const char* image, int room, int left, int top, int right, int bottom)
{
	type = OBJ_TILE;
	roomNumber = room;

	if(tileType == TILE_BACKGROUND)
	{
		solid = false;
		spawnPointOn = false;
		TILEtype = 1;
	}
	else if(tileType == TILE_COLLISION)
	{
		solid = true;
		spawnPointOn = false;
		TILEtype = 2;
	}
	else if(tileType == TILE_TRIGGER)
	{
		solid = false;
		spawnPointOn = false;
		TILEtype = 3;
	}
	else if(tileType == TILE_SPAWN)
	{
		solid = false;
		spawnPointOn = true;
		TILEtype = 4;
	}

	l = left;
	r = right;
	t = top;
	b = bottom;

	SetX((float)x);
	SetY((float)y);
	SetWidth(width);
	SetHeight(height);

	tileEVENT = image;

	if(TILEtype == TILE_BACKGROUND)
	{
		TCHAR myimage[100];
		mbstowcs_s( nullptr, myimage, 100, "Graphics/TileSet.png"/*image*/, _TRUNCATE );
		SetTextureID(CSGD_TextureManager::GetInstance()->LoadTexture(myimage));
	}

	if( TILEtype == TILE_BACKGROUND )
		TileManager::GetInstance()->AddTile(this);
	else
		ObjectManager::GetInstance()->AddObject(this);
}

Tile::~Tile(void)
{
	if(GetTextureID() != -1)
	{
		CSGD_TextureManager::GetInstance()->UnloadTexture(GetTextureID());
		SetTextureID(-1);
	}
	if( TILEtype == TILE_BACKGROUND )
		TileManager::GetInstance()->RemoveTile(this);
	else
		ObjectManager::GetInstance()->RemoveObject(this);
}

void Tile::Render()
{
	// If it isn't an image tile, skip
	if( TILEtype != TILE_BACKGROUND )
		return;

	// Get the camera position
	int camx = GamePlayState::GetInstance()->GetCamX();
	int camy = GamePlayState::GetInstance()->GetCamY();
	int width = Game::GetInstance()->GetScreenWidth();
	int height = Game::GetInstance()->GetScreenHeight();

	// If it isn't on cam, skip
	if( GetX() + GetWidth() < camx || GetY() + GetHeight() < camy || GetX() > camx + width || GetY() > camy + height )
		return;

	// As long as there's an image, draw it
	if( Entity::GetTextureID() != -1 )
	{
		RECT rec = {l,t,r,b};
		onScreen = true;
		CSGD_TextureManager::GetInstance()->Draw(GetTextureID(),(int)GetX() - camx, (int)GetY() - camy,1,1,&rec);
	}
	else
		onScreen = false;
}

bool Tile::CheckCollision(IEntity* base) 
{
	// If this isn't a collidable tile, skip it
	if( !solid )	
		return false;

	// Check if colliding and the object is solid
	if(Entity::CheckCollision(base) == true)
	{
		if(base->GetType() == OBJ_PLAYER)
			EventSystem::GetInstance()->SendEvent(tileEVENT);
		return true;
	}
	return false;
}
